package xujiwen.transport.servlet;

import xujiwen.transport.bean.User;
import xujiwen.transport.Mgr.UserMgr;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import xujiwen.transport.util.locker.Password;

/**
 * Servlet implementation class for Servlet: Register
 * 
 */
public class ModifPassword extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ModifPassword() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	@Override
	protected void doPost(final HttpServletRequest request,final HttpServletResponse response) throws ServletException,IOException {
		final HttpSession session = request.getSession();
		final User user = (User)session.getAttribute("user");
		if (user==null){
			response.sendRedirect("login.html");
			System.out.println("未登陆");
			return ;
		}
		// 指明编码
		//request.setCharacterEncoding("GBK");
		try {
			//final Integer tid = Integer.parseInt(request.getParameter("old"));
			final String old = request.getParameter("old");
			
			final String newPassword = request.getParameter("new");
			
			final String newconfirm = request.getParameter("confirm");
			
			UserMgr userMgr = new UserMgr();
			
			//MD5 md5 = new MD5(); 

			// 判断旧密码是否正确
			if(!userMgr.IsPasswordExsit(Password.MD5(old), user.getUid()))
			{
				response.getWriter().println("password is wrong! please try again.");
				
				return ;
			}
			
			if(!newPassword.equals(newconfirm))
			{
				// 新密码不一致
				response.getWriter().println("the new password is not same! please try again.");
				return ;
			}
			userMgr.UpdatePassword(user.getUid(), Password.MD5(newPassword));
			
			System.out.println("修改成功");	
		} catch(final NumberFormatException nfex){
			System.out.println("提交错误");			
			return ;
		}
		// 修改完毕跳到主页
		// 新密码不一致
		response.getWriter().println("password modifeded succeed!");
	}
}